package com.jiuli.liping.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jiuli.liping.dao.MoveHisDao;
import com.jiuli.liping.dao.ProductDao;
import com.jiuli.liping.dao.ProductOrderDao;
import com.jiuli.liping.dao.UserlistDao;
import com.jiuli.liping.service.UserlistService;
import com.jiuli.liping.service.WeiXinService;
import com.jiuli.liping.util.WeiXinUtils;
import com.jiuli.liping.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author zyl
 * Date  2019-12-03
 */
@Service
public class WeiXinServiceImpl implements WeiXinService {
    @Autowired
    private UserlistService userlistService;
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private MoveHisDao moveHisDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private UserlistDao userlistDao;
    @Value("${number}")
    private String number;

    public static String access_token =null;
    public static Date access_token_date = null;

    /**
     * 从微信获得access_token
     * @return
     */
    public  String getToken(){
        String token="";
        //1、判断access_token是否存在，不存在的话直接申请
        //2、判断时间是否过期，过期(>=7200秒)申请，否则不用请求直接返回以后的token
        if(null==access_token||"".equals(access_token)||(new Date().getTime()-access_token_date.getTime())>=(4000*1000)){
            try {
                String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=HUa2iRAJUJyYWWHqF_ZaegNYPwAVxgMjJG903cvmkTM";

                JSONObject jsonss = WeiXinUtils.getWeiXinApi(urls);

                //设置全局变量
                access_token=jsonss.toString();
                access_token_date=new Date();

                token=jsonss.toString();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            token=access_token;
        }
        return token;
    }

    public  String getToken2(){
        String token="";
        //1、判断access_token是否存在，不存在的话直接申请
        //2、判断时间是否过期，过期(>=7200秒)申请，否则不用请求直接返回以后的token
        if(null==access_token||"".equals(access_token)||(new Date().getTime()-access_token_date.getTime())>=(4000*1000)){
            try {
                String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=AJe6FSek8eeFSsBbUnTROgXm7vi-zT9OPPohRxv8DoE";

                JSONObject jsonss = WeiXinUtils.getWeiXinApi(urls);

                //设置全局变量
                access_token=jsonss.toString();
                access_token_date=new Date();

                token=jsonss.toString();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            token=access_token;
        }
        return token;
    }

    //获得token的json串
//    public String getToken(){
//        try {
//            //String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=4hRqvR3e0zY3Lgn5OtbfFKlYbBKDRpuz-qwx1X7DJ_c";
//           // String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=memyUeFwa-wkNsbxuJ9KC0iyiQyFef523ebl6YScgus";
//           // String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=HUa2iRAJUJyYWWHqF_ZaetJm5gRzLYVUFXjDEjXNg0k";
//            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=HUa2iRAJUJyYWWHqF_ZaegNYPwAVxgMjJG903cvmkTM";
//            //String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=vM_OkjyXfay0d-1hcLHltf_anLfni8L9vAy1cxCyZHM";
//
//            JSONObject jsonss = WeiXinUtils.getWeiXinApi(urls);
//            return jsonss.toString();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "fail";
//    }

    //获得访问user的详细信息
    public UserInfo getUserInfo(String code) {
        UserInfo userInfo = new UserInfo();
        try {
            //获得token    json串开始
            String token = getToken();
            //解析json
            JSONObject json = JSONObject.parseObject(token);
            AccessToken accessToken = new AccessToken();
            accessToken.setAccess_token(json.getString("access_token"));
            //获得token    json串结束

            //获得useridjson串开始
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken.getAccess_token()+"&"+code;
            JSONObject jsonss = WeiXinUtils.getWeiXinApi(urls);

            //获得user详细信息开始
            //解析json，获得userid
            JSONObject json2 = JSONObject.parseObject(jsonss.toString());
            Members members = new Members();
            members.setUserId(json2.getString("UserId"));
            String urls2 = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken.getAccess_token()+"&userid="+members.getUserId();
            System.out.println("返回信息1"+urls2);
            JSONObject jsonss2 = WeiXinUtils.getWeiXinApi(urls2);

            //获得user详细信息结束，返回json串
            JSONObject json3 = JSONObject.parseObject(jsonss2.toString());
            System.out.println("返回信息4"+json3.toString());
            if(!("0".equals(json3.getString("errcode")))){
                System.out.println("返回信息2"+jsonss2.toString());
                userInfo.setFlag(1);
                userInfo.setMessage("调用失败"+jsonss2.toString()+"3");
                return userInfo;
            }
            //position就是08851
            Userlist ul = new Userlist();
            ul.setWechatId(json3.getString("userid"));
            ul.setUserName(json3.getString("name"));
            String newPosition = WeiXinUtils.autoGenericCode(json3.getString("position"),5);
            ul.setUserNum(newPosition);
            ul.setAvatar(json3.getString("avatar"));
            ul.setThumb_avatar(json3.getString("thumb_avatar"));
            ul.setMobile(json3.getString("mobile"));

            int flagJur = userlistDao.getCountJur(json3.getString("position"),"1");
            int flagJur2 = userlistDao.getCountJur(json3.getString("position"),"2");
            int flagJur3 = userlistDao.getCountJur(json3.getString("position"),"3");
            //if(json3.getString("position").equals(number) || json3.getString("position").equals("08151") || json3.getString("position").equals("08851"))
            if(flagJur==1)
                ul.setJurisdictionId(2);// 2:商城管理员权限
            else if(flagJur2==1)
                ul.setJurisdictionId(3);// 3:前台管理员权限
            else if(flagJur3==1)
                ul.setJurisdictionId(4);// 4:食堂管理员权限
            else
                ul.setJurisdictionId(1);// 1:普通权限
            Timestamp nowTime = new Timestamp(System.currentTimeMillis());
            ul.setCreatTime(nowTime);
            //部门
            List<Userlist> userHr = userlistService.getDepartMentByHR(ul.getUserNum());
            if(userHr.size()>0) {
                String dp="";
                for (Userlist use: userHr) {
                    dp+=use.getDepartmentDescribe()+",";
                }
                if(dp!="")
                    ul.setDepartmentDescribe(dp.substring(0,dp.length()-1));
            }else{
                ul.setDepartmentDescribe("");
            }
            int fl = userlistService.getCount(ul);
            if(fl==0) {
                ul.setLastTime(nowTime);
                userlistService.insert(ul);
            }else if(fl==1){
                ul.setLastTime(nowTime);
                userlistService.update(ul);
            }
            //userInfo.setPosition(json3.getString("position"));
            userInfo.setFlag(0);
            userInfo.setUserlist(ul);
            userInfo.setMessage("调用成功");
            return userInfo;
        } catch (Exception e) {
            System.out.println("token异常1:"+e);
            e.printStackTrace();
        }
        userInfo.setFlag(1);
        userInfo.setMessage("调用失败");
        System.out.println("token异常2");
        return userInfo;
    }

    public static void main(String[] args) {
        JSONObject jsonss = null;
        try {
            //String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=4hRqvR3e0zY3Lgn5OtbfFKlYbBKDRpuz-qwx1X7DJ_c";
            // String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=memyUeFwa-wkNsbxuJ9KC0iyiQyFef523ebl6YScgus";
            // String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=HUa2iRAJUJyYWWHqF_ZaetJm5gRzLYVUFXjDEjXNg0k";
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret=vM_OkjyXfay0d-1hcLHltf_anLfni8L9vAy1cxCyZHM";
            jsonss = WeiXinUtils.getWeiXinApi(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获得token    json串开始
        String token = jsonss.toString();
        //解析json
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();
        String param = "{" +
                "\"touser\" :\""+1178+"\" ," +
                "\"msgtype\" : \"text\", "+
                "\"agentid\" : 1000050, "+
                "\"text\" : { \"content\" : \""+1+"\" },"+
                "\"safe\" : 0, "+
                "\"enable_id_trans\" : 0, "+
                "\"enable_duplicate_check\" : 0, " +
                "}";
        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
        int a =0;
    }
    
    /**
     * 消息推送
     */
    @Override
    public String sendMessage() {
        //获得token    json串开始
        String token = getToken();
        //解析json
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();
        String param = "{" +
                "\"touser\" :\""+1178+"\" ," +
                "\"msgtype\" : \"text\", "+
                "\"agentid\" : 1000044, "+
                "\"text\" : { \"content\" : \""+1+"\" },"+
                "\"safe\" : 0, "+
                "\"enable_id_trans\" : 0, "+
                "\"enable_duplicate_check\" : 0, " +
                "}";
        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
        return json1;
    }

    @Override
    public Message PassFlow(String orderId, String userId) {
        Message message=new Message();
        String orderStatus = productOrderDao.getStatusByFive(orderId);
        if("5".equals(orderStatus)){
            message.setFlag("failed");
            message.setMessage("改审批单子已过期，库存已释放");
            return message;
        }
        //productOrderDao.PassFlow(orderId);
        String orderDetail = productOrderDao.getOrderDetail(orderId);
        String wecharId = userlistDao.getWecharId(String.format("%05d",Integer.valueOf(userId)));
        String token = getToken();
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();
        String param = "{" +
                "\"touser\" :\""+wecharId+"\" ," +
                "\"msgtype\" : \"text\", "+
                "\"agentid\" : 1000044, "+
                "\"text\" : { \"content\" : \""+orderDetail+"\" },"+
                "\"safe\" : 0, "+
                "\"enable_id_trans\" : 0, "+
                "\"enable_duplicate_check\" : 0, " +
                "}";
        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
        List<ProductNumber> productNumbers = productDao.backNumber(orderId);
       /* for (int i=0;i<productNumbers.size();i++){
            int iceProductNumber = productDao.getIceProductNumber(productNumbers.get(i).getProductname());
            iceProductNumber=iceProductNumber-Integer.parseInt(productNumbers.get(i).getProductnumber());
            productDao.addNumber(productNumbers.get(i).getProductname(),iceProductNumber+"");
        }*/
        productOrderDao.PassFlow(orderId);
        message.setFlag("success");
        message.setMessage(json1);
        return message;
    }

    @Override
    public Message BackFlow(String orderId, String userId) {
        Message message=new Message();
        String orderStatus = productOrderDao.getStatusByFive(orderId);
        if("5".equals(orderStatus)){
            message.setFlag("failed");
            message.setMessage("改审批单子已过期，库存已释放");
            return message;
        }
        //productOrderDao.PassFlow(orderId);
            if (orderId!=null) {
                String wecharId = userlistDao.getWecharId(String.format("%05d", Integer.valueOf(userId)));
                String token = getToken();
                JSONObject json = JSONObject.parseObject(token);
                AccessToken accessToken = new AccessToken();
                accessToken.setAccess_token(json.getString("access_token"));
                //获得token    json串结束
                String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken.getAccess_token();
                String param = "{" +
                        "\"touser\" :\"" + wecharId + "\" ," +
                        "\"msgtype\" : \"text\", " +
                        "\"agentid\" : 1000044, " +
                        "\"text\" : { \"content\" : \"你的商城物品领用申请被驳回" + orderId + "\" }," +
                        "\"safe\" : 0, " +
                        "\"enable_id_trans\" : 0, " +
                        "\"enable_duplicate_check\" : 0, " +
                        "}";
                String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
                List<ProductNumber> productNumbers = productDao.backNumber(orderId);
                for (int i=0;i<productNumbers.size();i++){
                    int iceProductNumber = productDao.getIceProductNumber(productNumbers.get(i).getProductname());
                    System.out.println("驳回冻结数量:" + iceProductNumber+"商品编号:"+productNumbers.get(i).getProductname());
                    iceProductNumber=iceProductNumber-Integer.parseInt(productNumbers.get(i).getProductnumber());
                    if (iceProductNumber<0){
                        MoveHis moveHis=new MoveHis();
                        moveHis.setType("驳回解冻异常");
                        moveHis.setCommodityNumber(productNumbers.get(i).getProductname());
                        moveHis.setNumber(productNumbers.get(i).getProductnumber());
                        moveHis.setUserName(orderId);
                        moveHisDao.save(moveHis);
                        iceProductNumber=0;
                    }
                    System.out.println("驳回解冻完成后数量:" + iceProductNumber+"商品编号:"+productNumbers.get(i).getProductname());
                    productDao.addNumber(productNumbers.get(i).getProductname(),iceProductNumber+"");
                    MoveHis moveHis=new MoveHis();
                    moveHis.setType("驳回解冻");
                    moveHis.setCommodityNumber(productNumbers.get(i).getProductname());
                    moveHis.setNumber(productNumbers.get(i).getProductnumber());
                    moveHis.setUserName(orderId);
                    moveHisDao.save(moveHis);
                }
                productOrderDao.BackFlow(orderId);
                message.setFlag("success");
                message.setMessage(json1);
            }else {
                message.setFlag("success");
                message.setMessage("调用失败");
            }

        return message;
    }

    @Override
    public Message sendMsg(String userCode, String message) {
        Message message1=new Message();
        String[] split = userCode.split(",");
        List<String> vwIds=new ArrayList<>();
        for (String x:split){
            String wecharId = userlistDao.getWecharId(x);
            vwIds.add(wecharId);
        }
        if (vwIds.size()==0){

            message1.setFlag("N");
            message1.setMessage("未能获取到该人员对应的微信id");
            return message1;
        }


        String join = String.join("|", vwIds);

        String token = getToken2();
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();
        String param = "{" +
                "\"touser\" :\""+join+"\" ," +
                "\"msgtype\" : \"text\", "+
                "\"agentid\" : 1000039, "+
                "\"text\" : { \"content\" : \""+message+"。\" },"+
                "\"safe\" : 0, "+
                "\"enable_id_trans\" : 0, "+
                "\"enable_duplicate_check\" : 0, " +
                "}";
        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
        message1.setFlag("S");
        message1.setMessage("推送成功:"+json1);
        return message1;
    }

    /**
     * 库存预警推送消息
     * @return
     */
    @Override
    public int sendKunChunYuJing(Commodity commodity2,int fbk2) {
        String name = getPropertyNameTo(commodity2);

        String token = getToken();
        JSONObject json = JSONObject.parseObject(token);
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        //获得token    json串结束
        String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();
        String param = "{" +
                "\"touser\" :\""+3846+"\" ," +
                "\"msgtype\" : \"text\", "+
                "\"agentid\" : 1000044, "+
                "\"text\" : { \"content\" : \""+name+"库存预警提醒,还剩:"+fbk2+"。\" },"+
                "\"safe\" : 0, "+
                "\"enable_id_trans\" : 0, "+
                "\"enable_duplicate_check\" : 0, " +
                "}";
        String json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
        return 1;
    }

    @Override
    public Message sendMessageWx(WxSendVo wxSendVo) {
        Message message = new Message();
        if(StringUtils.isEmpty(wxSendVo.getSecret())){
            message.setFlag("failed");
            message.setMessage("参数secret为空");
            return message;
        }
        if(wxSendVo.getUserIds()==null){
            message.setFlag("failed");
            message.setMessage("参数userIds为空");
            return message;
        }
        if(StringUtils.isEmpty(wxSendVo.getContent())){
            message.setFlag("failed");
            message.setMessage("参数content为空");
            return message;
        }
        if(StringUtils.isEmpty(wxSendVo.getAgentid())){
            message.setFlag("failed");
            message.setMessage("参数agentid为空");
            return message;
        }
        List<Integer> wecharIds =new ArrayList<>();
        for (Integer userId:wxSendVo.getUserIds()) {
            Integer wecharId = userlistDao.getWecharIdWx(String.format("%05d",Integer.valueOf(userId)));
            if(wecharId==null){
                message.setFlag("failed");
                message.setMessage("参数"+userId+"系统找不到weCharId");
                return message;
            }
            wecharIds.add(wecharId);
        }
        JSONObject jsonss=null;
        try {
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwef2fadef61221778&corpsecret="+wxSendVo.getSecret();
            jsonss = WeiXinUtils.getWeiXinApi(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject json = JSONObject.parseObject(jsonss.toString());
        AccessToken accessToken = new AccessToken();
        accessToken.setAccess_token(json.getString("access_token"));
        String json1="";
        for (Integer wecharId: wecharIds) {
            //获得token    json串结束
            String urls = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken.getAccess_token();
            String param = "{" +
                    "\"touser\" :\""+wecharId+"\" ," +
                    "\"msgtype\" : \"text\", "+
                    "\"agentid\" : "+wxSendVo.getAgentid()+", "+
                    "\"text\" : { \"content\" : \""+wxSendVo.getContent()+"\" },"+
                    "\"safe\" : 0, "+
                    "\"enable_id_trans\" : 0, "+
                    "\"enable_duplicate_check\" : 0, " +
                    "}";
            json1 = WeiXinUtils.getWeiXinApiPost(urls, param);
        }
        message.setFlag("success");
        message.setMessage(json1);
        return message;
    }

    //属性拼接
    public String getPropertyNameTo(Commodity commodity){
        String name="";
        if(!(StringUtils.isEmpty(commodity.getProperty1Name()))){name+=commodity.getProperty1Name() +":"+commodity.getProperty1()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty2Name()))){name+=commodity.getProperty2Name() +":"+commodity.getProperty2()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty3Name()))){name+=commodity.getProperty3Name() +":"+commodity.getProperty3()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty4Name()))){name+=commodity.getProperty4Name() +":"+commodity.getProperty4()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty5Name()))){name+=commodity.getProperty5Name() +":"+commodity.getProperty5()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty6Name()))){name+=commodity.getProperty6Name() +":"+commodity.getProperty6()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty7Name()))){name+=commodity.getProperty7Name() +":"+commodity.getProperty7()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty8Name()))){name+=commodity.getProperty8Name() +":"+commodity.getProperty8()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty9Name()))){name+=commodity.getProperty9Name() +":"+commodity.getProperty9()+",";}
        if(!(StringUtils.isEmpty(commodity.getProperty10Name()))){name+=commodity.getProperty10Name() +":"+commodity.getProperty10()+",";}
        name = name.substring(0,name.length()-1);
        if(StringUtils.isEmpty(name)){
            name="无";
        }
        String name1 = commodity.getCommodityFatherName()+"("+name+")";
        return name1;
    }
}
